//
//  FANComposeViewController.swift
//  Weibo - Swift
//
//  Created by user on 16/4/25.
//  Copyright © 2016年 user. All rights reserved.
//

import UIKit
import SVProgressHUD

class FANComposeViewController: UIViewController,UINavigationControllerDelegate,UIImagePickerControllerDelegate {

    lazy var titleView:UILabel = {
    
        let titleView = UILabel()
        
        titleView.numberOfLines = 0
        
        titleView.textAlignment = .Center
        
        titleView.font = UIFont.systemFontOfSize(16)
        
        if let name = FANUserNetModel.sharedUserModel.account?.name{
            
            let text = "发微博\n\(name)"
            
            let range = (text as NSString).rangeOfString(name)
            
            let attr = NSMutableAttributedString(string: text)
            
            attr.addAttributes([NSForegroundColorAttributeName:UIColor.darkGrayColor(),NSFontAttributeName:UIFont.systemFontOfSize(13)], range: range)
            
            titleView.attributedText = attr
            
        }else{
            
            titleView.text = "发微博"
        }
        
        titleView.sizeToFit()
    
        return titleView
    
    }()
    
    lazy var rightButton:UIButton = {
    
        
        let button = UIButton()
        
        button.setBackgroundImage(UIImage(named: "common_button_white_disable"), forState: UIControlState.Disabled)
        button.setBackgroundImage(UIImage(named: "common_button_orange_highlighted"), forState: UIControlState.Highlighted)
        button.setBackgroundImage(UIImage(named: "common_button_orange"), forState: UIControlState.Normal)
        
        button.titleLabel?.font = UIFont.systemFontOfSize(15)
        
        button.setTitle("发送", forState: UIControlState.Normal)
        
        button.setTitleColor(UIColor.darkGrayColor(), forState: UIControlState.Disabled)
        
        button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        
        button.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Highlighted)
        
        button.frame.size = CGSize(width: 48, height: 25)
        
        button.addTarget(self, action: "sendMessage", forControlEvents: UIControlEvents.TouchUpInside)
        
        return button
    }()
    
    @objc private func sendMessage(){
    
        if addPictureView.hidden {
            
            sendTextWeibo()
            
        }else{
            
            sendImageWeibo()
        }
        
    }
    
    func sendImageWeibo(){
        
        let urlString = "https://upload.api.weibo.com/2/statuses/upload.json"
        
        let params = [
            
            "access_token" : FANUserNetModel.sharedUserModel.accessToken ?? "",
            "status" : textView.emoticonText!
            
        ]
        
        let data = UIImagePNGRepresentation(self.addPictureView.imageArray.first!)!
        
        NetworkTools.sharedTools.update(urlString, parameter: params, datas: ["pic":data]) { (responseObject, error) -> () in
            
            if error == nil{
                
                SVProgressHUD.showSuccessWithStatus("发送成功")
                
            }else{
                
                SVProgressHUD.showErrorWithStatus("发送失败")
                
                print(error)
            }
        }
        
    }
    
    func sendTextWeibo(){
        
        let urlString = "https://api.weibo.com/2/statuses/update.json"
        
        let params = [
        
            "access_token" : FANUserNetModel.sharedUserModel.accessToken ?? "",
            "status" : textView.emoticonText!
        ]
        
        NetworkTools.sharedTools.request(FANRequestMethod.post, urlString: urlString, parameter: params, progress: nil) { (responseObject, error) -> () in
            
            if error == nil{
                
                SVProgressHUD.showSuccessWithStatus("发送成功")
                
            }else{
                
                SVProgressHUD.showErrorWithStatus("发送失败")
                
                print(error)
            }
        }
        
    }
    
   
    
    lazy var textView:FANTextView = {
    
        let textView = FANTextView()
        
        textView.keyboardDismissMode = .OnDrag
        
        textView.alwaysBounceVertical = true
        
        return textView
    
    }()
    
    lazy var composeTools:FANComposeTools = {
    
        let composeTools = FANComposeTools(frame: CGRectZero)
        
        composeTools.callBackClosure = { [weak self] (type:FANComposeToolBarButtonType) in
            
            switch type{
                
            case .Picture:
                
                self?.selectPicture()
                
                break
                
            case .Mention:
                
                break
            case .Trend:
                
                break
            case .Emoticon:
                
                self?.touchEmotion()
                
                break
            case .Add:
                
                break
            
            }
        }
        
        return composeTools
    }()
    
    lazy var emoticonView:FANKeyboardView = {
    
        let emoticonView = FANKeyboardView()
        
        emoticonView.frame.size = CGSize(width: ScreenW, height: 216)
        
        return emoticonView
    }()
    
    lazy var addPictureView:FANSendPictureView = {
    
        let addPictureView = FANSendPictureView(frame: CGRectZero, collectionViewLayout:UICollectionViewFlowLayout())
    
        addPictureView.didAddClosure = { [weak self] in
            
            self?.selectPicture()
        }
        
        return addPictureView
        
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()

        setupUI()
    }
    
    func touchEmotion(){
        
        if textView.inputView == nil{
            
            textView.inputView = self.emoticonView
            
        }else{
            
            textView.inputView = nil
        }
        
        textView.reloadInputViews()

    }
    
    func selectPicture(){
        
         let imagePickerVc = UIImagePickerController()
        
        imagePickerVc.delegate = self
        
        self.presentViewController(imagePickerVc, animated: true, completion: nil)
    }
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        addPictureView.addImage(image.scaleToWidth(600))
        
        picker.dismissViewControllerAnimated(true, completion: nil)
    }
    
  
    
    func setupUI(){
        
        view.backgroundColor = UIColor.whiteColor()
        
        setupNav()
        
        self.view.addSubview(textView)
        
        textView.placeHolder = "分享新鲜事..."
        
        textView.delegate = self
        
        textView.font = UIFont.systemFontOfSize(15)
        
        textView.snp_makeConstraints { (make) -> Void in
            
            make.edges.equalTo(self.view)
        }
        
        self.view.addSubview(self.composeTools)
        
        composeTools.snp_makeConstraints { (make) -> Void in
            
            make.leading.bottom.trailing.equalTo(self.view)
            
            make.height.equalTo(44)
        }
        
        textView.addSubview(addPictureView)
        
        addPictureView.snp_makeConstraints { (make) -> Void in
            
            make.top.equalTo(100)
            
            make.leading.equalTo(5)
            
            make.width.equalTo(textView).offset(-10)
            
            make.height.equalTo(textView.snp_width)
        }
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChangeFrame:", name: UIKeyboardWillChangeFrameNotification, object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "EmoticonButtonClick:", name: "FANEmoticonButtonClickNotification", object: nil)
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "getDelectedButton:", name: "FANDidDelectedNSNotification", object: nil)
    }
    
    @objc private func getDelectedButton(noti:NSNotification){
    
        self.textView.deleteBackward()
    
    }
    
    @objc private func EmoticonButtonClick(noti:NSNotification){
        
        let emoticon = noti.userInfo!["emoticon"] as! FANEmoticon
        
        
        if emoticon.type == "1" {
            
            self.textView.insertText(emoticon.code!.emoji())
            
        }else{
            
//            print("按图片表情")
            
            self.textView.insertEmoticon(emoticon)
        }
    }
    
    @objc private func keyboardChangeFrame(noti:NSNotification){
        
        /*
        NSConcreteNotification 0x7f841b4827d0 {name = UIKeyboardDidChangeFrameNotification; userInfo = {
        UIKeyboardAnimationCurveUserInfoKey = 7;
        UIKeyboardAnimationDurationUserInfoKey = "0.25";
        UIKeyboardBoundsUserInfoKey = "NSRect: {{0, 0}, {375, 258}}";
        UIKeyboardCenterBeginUserInfoKey = "NSPoint: {187.5, 796}";
        UIKeyboardCenterEndUserInfoKey = "NSPoint: {187.5, 538}";
        UIKeyboardFrameBeginUserInfoKey = "NSRect: {{0, 667}, {375, 258}}";
        UIKeyboardFrameEndUserInfoKey = "NSRect: {{0, 409}, {375, 258}}";
        UIKeyboardIsLocalUserInfoKey = 1;
        }}
        */
        
         let keyRect = (noti.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        
        
        composeTools.snp_updateConstraints { (make) -> Void in
            
            make.bottom.equalTo(keyRect.origin.y - ScreenH)
        }
        
//        print(keyRect.origin.y - ScreenH)
        
        UIView.animateWithDuration(0.25) { () -> Void in
            
            self.view.layoutIfNeeded()
        }
        
    }
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        textView.becomeFirstResponder()
    }
    
    func setupNav(){
        
        navigationItem.leftBarButtonItem  = UIBarButtonItem(title: "取消", style: .Plain, target: self, action: "back")
        
        navigationItem.rightBarButtonItem = UIBarButtonItem(customView: rightButton)
        
        navigationItem.rightBarButtonItem?.enabled = false
        
        setupTitleView()
        
    }
    
    func setupTitleView(){
        
        navigationItem.titleView = titleView
    }
    
    func back(){
        
        textView.resignFirstResponder()
        
        self.dismissViewControllerAnimated(true, completion: nil)
    }

}

extension FANComposeViewController:UITextViewDelegate{
    
    func textViewDidChange(textView: UITextView) {
        
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
    }
}
